const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');

/**
 * 启动chrome浏览器，不打开 browser 窗口
 */
async function launchChromeHeadless() {
    let chrome;
    try {
        chrome = await chromeLauncher.launch({
            chromeFlags: [
                "--headless"
            ],
            enableExtensions: true,
            logLevel: "error"
        });
        return chrome;
    } catch (error) {
        console.log("Error while launching Chrome")
    }
}

/**
 * 运行 lighthouse
 * @param {*} url 
 * @param {*} opts 
 * @param {*} config 
 */
async function runLighthouse(url, opts = null, config = null, chrome) {
    try {
        let opts;
        if (chrome) {
            opts.port = chrome.port;
            config.locale = "zh";
            let result = await lighthouse(url, opts, config);
            chrome.kill();
            return result.lhr;
        }
    } catch (error) {
        console.log('Error while run Lighthouse test: ', error)
    }
}

/**
 * 
 * @param {*} url 被测网站地址
 * @param {*} config lighthouse 性能测试配置项
 */
async function launchChromeAndRunLighthouse(url, config = null) {
    let opts = {
        chromeFlags: [
            "--headless"
        ],
        logLevel: "error",
    }
    let chrome;
    try {
        //启动一个chrome的instance，提供给lighthouse，--headless表示不打开浏览器窗口
        chrome = await chromeLauncher.launch({ chromeFlags: opts.chromeFlags });
        opts.port = chrome.port;
        opts.locale = "zh";

        let result = await lighthouse(url, opts, config);
        return result.lhr;
    } catch (error) {
        console.log("Error while launching Chrome or running Lighthouse test", error);
    } finally {
        if (chrome) {
            await chrome.kill();
        }
    }
}

/**
 * 获取lighthouse报告中的性能指标数据
 * @param {*} result lighthouse报告
 */
function getIndicator(result) {
    if (result.audits) {
        let firtstContentfulPaint = result.audits['first-contentful-paint'].rawValue;
        let firtstMeaningfulPaint = result.audits['first-meaningful-paint'].rawValue;
        let firstCpuIdle = result.audits['first-cpu-idle'].rawValue;
        let speedIndex = result.audits['speed-index'].rawValue;
        let timeToInteractive = result.audits['interactive'].rawValue;
        let estimatedInputLatency = result.audits['estimated-input-latency'].rawValue;
        return { firtstContentfulPaint, firtstMeaningfulPaint, firstCpuIdle, speedIndex, timeToInteractive, estimatedInputLatency };
    } else {
        return null;
    }
}


module.exports = {
    launchChromeAndRunLighthouse,
    getIndicator
}